﻿@using KPIS.GERP.Models.ViewModel
@using KPIS.GERP.Models.ICM
@model IEnumerable<PrePurchaseRequest>

@{
    ViewBag.Title = "แจ้งความประสงค์ขอซื้อ/จ้าง [PP]";
    ViewBag.Descr = "หน่วยงานต่างๆ ส่งความประสงค์ขอซื้อ/จ้างเข้ามาที่งานพัสดุ";
    var filterJobSiteId = ViewBag.FilterJobSiteId as int?;
    var jobSiteSelectList = new KPIS.GERP.WEB.GIMS.JobsiteService.JobsiteServiceClient().LoadInternalJobSiteSelectList(GimsMembership.User.Employee.WorkingJobSiteId, true, 3);
    bool isThisUserAboveLevel3JobSite = true;
    var jobSiteSelectListHtmlAttribute = new Dictionary<string, object>
        {
            {
                "class", "chzn-select"
            },
            {
                "data-placeholder", "เลือกประเภทการจัดหา"
            }
        };
        
       if(isThisUserAboveLevel3JobSite)
       {
           jobSiteSelectListHtmlAttribute.Add("readonly", "");
       }
       
       if (CompareUtility.IsStringsEqual(Request["EmptyLayout"], "true") || CompareUtility.IsStringsEqual(Request["NoLayout"], "true") || GimsUtilities.ContentOnly)
        {
            Layout = "~/Views/Shared/_EmptyLayout.cshtml"; 
        }
       if (CompareUtility.IsStringsEqual(Request["EmptyLayout"], "true") || CompareUtility.IsStringsEqual(Request["NoLayout"], "true")  )
        { 
            ViewBag.EmptyLayout = true;
        }
}

@using (Html.BeginForm("DeleteAll", "PrePurchase", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    
    <p id="message"></p>
    
    <div class="row-fluid">    
        <div class="block-button-menu-above">
            <a class="btn button-standard-width btn-small btn-success" 
               data-rel="tooltip" 
                href="@Url.Action("Create", new {ViewBag.EmptyLayout})" 
               role="button" 
               data-original-title="" 
               title="สร้างคำขอแจ้งความประสงค์">
                <i class="icon-plus bigger-120"></i>&nbsp;&nbsp;เพิ่ม
            </a>
            @Html.ButtonDeleteAll()
            <!-- Filter -->
						@Html.DropDownList("filterJobSiteId", jobSiteSelectList, jobSiteSelectListHtmlAttribute)
            <!-- End Filter -->
        </div>

        @Html.ValidationSummary(true, "", new { @class = "alert alert-error" })

        <div class="row-fluid">
            <div class="table-header span12">
                <div class="span10"> 
                    @ViewBag.Title 
                </div>
                @Html.Partial("_ExportButton") 
            </div>
        </div>

        <table id="table" class="table table-striped table-bordered table-hover" aria-describedby="table_info">
            <thead>
                <tr>
                    <th class="center" style="width:24px;">
						<!-- Check box delete multiple records column-->
                        <label>
                            <input type="checkbox" />
                            <span class="lbl"></span>
                        </label>
                    </th>
                    <th style="text-align: center; width: 100px;">
                        เลขแจ้งความประสงค์
                    </th>
                    <th style="text-align: center">
                        @Html.DisplayNameFor(model => model.Name)
                    </th>
                    <th style="text-align: center; width:70px;">
                        @Html.DisplayNameFor(model => model.MasPurchaseType.PcTypeName)
                    </th>
                    <th style="text-align: center; width:70px;">
                        @Html.DisplayNameFor(model => model.RequestDate)
                    </th>
                    <th style="text-align: center; width:70px;">
						@KPIS.GERP.Models.Class.LookupUtility.GetLookupNameFromAllLookup(KPIS.GERP.Models.ICM.IcmMasLookUpType.LookUpType.Priority)
                    </th> 
                    <th style="text-align: center; width:85px;">
                        @Html.DisplayNameFor(model => model.RecordStatus)
                    </th>
					<th class="center" style="width:20px;">
						<!-- Empty head column for export buttons -->&nbsp;
					</th>
                </tr>
            </thead>
            @{
    GERPContext db = new GERPContext();
    var pprItems = db.PrePurchaseRequestItems
        .Include("ProjectOperationExpense.ProjectExpense.MasBudgetSource")
        .Include("ProjectOperationExpense.ProjectExpense.Project")
        .ToList();

    var projectService = new KPIS.GERP.WEB.GIMS.ProjectOperationService.ProjectOperationServiceClient();
            }
            <tbody>
                @foreach (var m in (Model ?? new List<PrePurchaseRequest>()).OrderByDescending(o => o.PprId))
                {
                    <tr> 
                        <td class="center">
                            <!-- Check box all for delete multiple records -->
                            @if (m.RecordStatus == KPIS.GERP.Models.SYS.RecordStatus.ApprovedStatus)
                            {
                                <label>
                                    <input type="checkbox" name="deleteIds" value="@(m.PprId)" disabled />
                                    <span class="lbl"></span>
                                </label>
                            }
                            else
                            {
                                <label>
                                    <input type="checkbox" name="deleteIds" value="@(m.PprId)" />
                                    <span class="lbl"></span>
                                </label>
                            }
                        </td>
                        <td style="text-align: center"> 
                            @Html.ActionLink(m.Code ?? "-", "Details", new
                                {
                                    Id = m.PprId,
                                    _ = m.Code + "-" + (m.Name ??"").Trim().Replace(" ", "")
                                })
                        </td>
                        <td style="font-weight: bold">
                                                        @Html.ActionLink(@m.Name, "Details", new
                                {
                                    Id = m.PprId,
                                    _ = m.Code + "-" + (m.Name ?? "").Trim().Replace(" ", "")
                                }, new
                                    {
                                        style = "font-family:tahoma;"
                                    })
                            @{
                                List<string> bgSourceNames = new List<string>();
                                var pprItemsInPr = pprItems.Where(o => o.PprId == m.PprId);
                            }
                            @foreach (var pprItem in pprItemsInPr)
{
    if (pprItem != null &&
        pprItem.ProjectOperationExpense != null &&
        pprItem.ProjectOperationExpense.ProjectExpense != null &&
        pprItem.ProjectOperationExpense.ProjectExpense.MasBudgetSource != null)
    {
        if (!bgSourceNames.Exists(o => o == pprItem.ProjectOperationExpense.ProjectExpense.MasBudgetSource.Name))
        {
            bgSourceNames.Add(pprItem.ProjectOperationExpense.ProjectExpense.MasBudgetSource.Name);
        }
    }
}
                            <i style=" font-weight:normal; ">@if (bgSourceNames.Any())
                                {
                                    @:(@string.Join(", ", bgSourceNames.ToArray()))
                                }
                                else if (!bgSourceNames.Any() && !pprItemsInPr.Any())
                                {
                                    @:(-ยังไม่เลือกรายการพัสดุ-)
                                }
                                else if (!bgSourceNames.Any() && pprItemsInPr.Any())
                                { 
                                    @:(-ไม่สามารถดึงแหล่งเงินได้-)
                                }
                               </i>
                        </td>
                        <td style="text-align: center; width: 60px" >
                            @Html.DisplayFor(model => m.MasPurchaseType.PcTypeName)
                        </td>
                        <td style="text-align: center">
                            <span style="display: none">@m.RequestDate.ToDbFormat()</span>@m.RequestDate.ToShortDateStringBuddhist()
                        </td>
                        <td style="text-align: center"> 
                            @if (m.Priority.LookUpName == "ปกติ")
                            {
                                @Html.Raw("<font color='green'>")
                            }
                            else
                            {
                                @Html.Raw("<font color='red'>")
                            }
                            @Html.DisplayFor(model => m.Priority.LookUpName)
                            @Html.Raw("</font>")
                        </td> 
                        <td style="text-align: center; font-weight: bold">
                            <span class="recordstatus-@m.RecordStatus">
                                @RecordStatus.RecordStatusName(m.RecordStatus)
                            </span>
                        </td>
                        <td class="td-actions">
                            @if (m.RecordStatus == RecordStatus.WaitStatus || m.RecordStatus == KPIS.GERP.Models.SYS.RecordStatus.ReturnedStatus)
                            {
                                @Html.Partial("_ButtonMenuEachRow", new ExportGrid
                                    {
                                        Id = m.PprId,
                                        DetailsUrl = Url.Action("Details") + "/" + m.PprId,
                                        EditUrl = Url.Action("Edit") + "/" + m.PprId,
                                        DeleteUrl = Url.Action("Delete") + "/" + m.PprId
                                    })
                            }
                            else
                            {
                                @Html.Partial("_ButtonMenuEachRow", new ExportGrid
                                    {
                                        Id = m.PprId,
                                        DetailsUrl = Url.Action("Details") + "/" + m.PprId
                                    })
                            }
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
}

@section scripts {
    
	<script type="text/javascript">
	    $(function () {
	        
	        
		    var oTable1 = $('#table').dataTable(
		        {
		            "aaSorting": [[0, "desc"]]  
		            , "oTableTools": {
		                "aButtons": [
                            "copy",
                            //"print",
                            //{
                            //    "sExtends": "collection",
                            //    "sButtonText": "Save",
                            //    "aButtons": ["csv", "xls", "pdf"]
                            //}
		                ]
		            },
		            "aoColumns": [ 
                        { "bSortable": false },
                        { "bSortable": true },
                        { "bSortable": true },
                        { "bSortable": true },
                        { "bSortable": true },
                        { "bSortable": true },
                        { "bSortable": true },
                        { "bSortable": false }
		            ]
		        });

		    //var oTableTools = new TableTools(oTable1, {
		    //    "buttons": [
            //        "copy",
            //        "csv",
            //        "xls",
            //        "pdf",
            //        { "type": "print", "buttonText": "Print me!" }
		    //    ]
		    //});

		    // $('#table').before(oTableTools.dom.container);



		    $('#filterJobSiteId').on('change', function() {
		        window.location = '@Url.Action("Index", "PrePurchase")/?' + $(this).val();
		    });
		     
			$('table th input:checkbox').on('click', function () {
				var that = this;
				$(this).closest('table').find('tr > td:first-child input:checkbox').not(":disabled")
				.each(function () {
					this.checked = that.checked;
					$(this).closest('tr').toggleClass('selected');
					
				});

			});

			$('[data-rel=tooltip]').tooltip();

			$("form").submit(function () {
				var currentForm = this;
				bootbox.confirm(function (result) {
					var _result = result;
					if (result) {
						$.ajax({
							url: "DeleteAll",
							type: "post",
							dataType: "json",
							data: $(currentForm).serialize(),
							success: function (result) {
								if (result.success) {
									location.reload();
								}
								else {
								}
							}
						});
					}
				})
				return false;

			});

		})

	</script>

}